package part1.four;

/**
 * @Author: shaochong
 * @Date: 2021/8/6
 * @Description:
 */
public class Solution4 {
    public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
        // nums1数组指针
        int i = 0;
        // nums数组指针
        int j = 0;
        // 定义额外数组
        int sum = nums1.length + nums2.length;
        int[] arr = new int[sum];

        // k = m + n,因为两个数组是有序的所以只需要遍历一次即可以得到有序的arr数组
        for(int k = 0; k < sum; k++) {
            if (i < nums1.length && j < nums2.length) {
                if (nums1[i] <= nums2[j]) {
                    arr[k] = nums1[i++];
                } else {
                    arr[k] = nums2[j++];
                }
            } else if (i < nums1.length) {
                arr[k] = nums1[i++];
            } else if (j < nums2.length) {
                arr[k] = nums2[j++];
            }
        }
        if (sum == 0) {
            return 0.00000;
        }
        if (sum % 2 != 0) {
            int position = (sum -1) / 2;
            return (double) Math.round(arr[position] * 10) / 10;
        } else {
            int pos1 = sum / 2;
            int pos2 = pos1 - 1;
            double all = arr[pos1] + arr[pos2];
            return (double) Math.round(all / 2 * 10) / 10;
        }
    }
    
    public static void main(String[] args) {
        int[] a = {1,2};
        int[] b = {3,4};
        double ans = findMedianSortedArrays(a, b);
        System.out.println(ans);
    }
}
